package com.financing.platform.web.api;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.financing.mail.dto.MailContentDTO;
import com.financing.platform.common.ResultMap;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.ILogsService;
import com.financing.platform.service.IUserInfoService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.vo.ProjectSendConfirmEmailVO;

public abstract class BaseAction {
	protected Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	protected ILogsService logsServiceImpl;
	
	@Autowired
	IFaUserService faUserServiceImpl;
	@Autowired
	IUserInfoService userInfoServiceImpl;
	

	@Value("#{settings['mongoDBLink']}")
	public String mongoDBLink;
	/**
	 * 返回结果
	 */
	ResultMap resultMap = new ResultMap();
	

	public MailContentDTO getEmailObject(List<ProjectSendConfirmEmailVO> sendList,UserInfoDTO user)
			throws SQLException {
		ProjectSendConfirmEmailVO beanFirst  = sendList.get(0);
		int rowspan = 0;
		ProjectSendConfirmEmailVO mailResult = null;
		ProjectSendConfirmEmailVO temp = null;
		List<Integer> tmp = new ArrayList<Integer>();
		String start = "";
		String end = "";
		// 邮件内容
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < sendList.size(); i++) {
			mailResult = sendList.get(i);
			rowspan = 0;
			for (int j = 0; j < sendList.size(); j++) {
				temp = sendList.get(j);
				if(mailResult.getPid().compareTo(temp.getPid()) == 0){
					rowspan ++;
				}
			}
			
			start = projectAmount(mailResult.getProjectStartAmount());
			end = projectAmount(mailResult.getProjectEndAmount());
			
			if(tmp.contains(mailResult.getPid())){
				sb.append(" <tr style='height: 50px;background-color:white;'>");
				sb.append("<td style='font-size:15px;'>" + start + "-" + end + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectCorePrice() + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectRabateProfit() + "</td>");
				sb.append("</tr>");
			}else{
				tmp.add(mailResult.getPid());
				sb.append(" <tr style='height: 50px;background-color:white;'>");
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + (tmp.size()) + "</td>");
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectName() + "</td>");
				sb.append("<td style='font-size:15px;'>" + start + "-" + end + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectCorePrice() + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectRabateProfit() + "</td>");
				//如果type为PEVC去掉大小配比
				if(!Dict.pevcProjectType.equals(mailResult.getpType())){
					sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectSizeRarioExplain() + "</td>");
				}
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectDueTime() + "月</td>");
				sb.append("<td rowspan='"+rowspan+"'>" + mailResult.getProjectRecruitmentSummary() + "</td>");
				sb.append("</tr>");
			}
		}
		sb.append("</table>");
		
	
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("accessCompany", beanFirst.getProjectAccessCompany());
		params.put("accessName", beanFirst.getProjectAccessName());
		params.put("sysDate", DateUtil.getDate("yyyy/MM/dd"));
		params.put("loginName",user.getUsername());
		params.put("loginMobile",user.getTelePhone());
		params.put("loginEmail",user.getEmail());
		params.put("content",sb.toString());
				
		Map<String,Object> m  = MessageUtil.getMessageInfo("mailTemplate","sendConfirmEmail",params);
		String title = (String)m.get(MessageUtil.KEY_TITLE);
		String content = (String)m.get(MessageUtil.KEY_CONTENT);
		//如果type为PEVC去掉大小配比
		if(Dict.pevcProjectType.equals(mailResult.getpType())){
			content=content.replace("<td width=\"142\" style=\"font-size:16px;\" >大小配比</td>", "");
		}
		MailContentDTO mail = new MailContentDTO();
		mail.setContext(content);
		mail.setRecAddress(beanFirst.getProjectAccessEmail());
		mail.setCc(user.getEmail());
		mail.setSubject(title);
		mail.setRequestTime(new Date());
		return mail;
	}
	public String projectAmount(BigDecimal amount){
		if(amount != null){
			return amount.compareTo(new BigDecimal(100000000)) >= 0 ? 
					amount.divide(new BigDecimal(100000000)) + "亿" : 
					(amount.compareTo(new BigDecimal(10000)) >= 0 ? 
							amount.divide(new BigDecimal(10000)) + "万" : 
							amount).toString();
		}
		return "";
	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public  Map getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
	    Map returnMap = new HashMap();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = values[i] + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}
	//获取登录的systemid判断是否部门负责人，如果是取出部门id查询 除admin  
	public void getSystemIsCurrent(HttpServletRequest request, Map map) {
			Object systemUserId=map.get("systemUserId");
			if(systemUserId!=null&&StringUtils.isNotBlank(systemUserId+"")){
				HttpSession session = request.getSession();
				UserInfoDTO userInfoDTO = (UserInfoDTO) session.getAttribute(DTOdateSet.user);
				if(!userInfoDTO.getUserNickname().equals("admin")){
					String userId = userInfoDTO.getUserId();
					if(systemUserId.equals(userId)){//默认当前用户  查询所有
						map.put("isCurrent", true);
					}
				}
			}
		}
		/***
		 * 获取用户机构下所有id
		 * @param map
		 * @throws SQLException
		 */
		public void getSystemIds(Map map) throws SQLException {
			Object systemUserId=map.get("systemUserId");
			Object isCurrent = map.get("isCurrent");
			if(systemUserId!=null&&StringUtils.isNotBlank(systemUserId+"")){
				String sysId = String.valueOf(systemUserId);
				
				List<String> systemUserIds = null;
				if(isCurrent==null){
					systemUserIds =userInfoServiceImpl.queryUserInfoSubUserId(sysId);
				}else{
					 systemUserIds = faUserServiceImpl.queryFaUserSubUserId(sysId);
				}
				if(systemUserIds.size()==0){
					systemUserIds.add(sysId);
				}
				StringBuffer sb=new StringBuffer();
				for (String s : systemUserIds) {
					if(StringUtils.isBlank(sb.toString())){
						if(StringUtils.isNotBlank(s)){
							sb.append("'"+s+"'");
						}
					}else{
						sb.append(","+"'"+s+"'");
					}
				}
				map.put("systemUserId", sb.toString());
			}
		}
		/***
		 * 网络请求   http
		 * @param url
		 * @return
		 * @throws MalformedURLException
		 * @throws IOException
		 */
		public String urlconnection(String u)
				throws MalformedURLException, IOException {
			URL url = new URL(u);
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			String string = IOUtils.toString(inputStream);
			return string;
		}
}
